﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Handy_WPF.MVVM
{
    /// <summary>
    /// 属性改变通知和数据验证
    /// </summary>
    public class NotificationProperty : INotifyPropertyChanged, IDataErrorInfo
    {
        #region 属性发生改变通知
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 发起通知
        /// </summary>
        /// <param name="propertyName">属性名</param>
        public void RaisePropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion

        #region 数据验证
        protected virtual string GetValidationErrors()
        {
            //验证上下文类实例化
            var vc = new ValidationContext(this, null, null);
            //验证请求的结果容器
            var vResults = new List<ValidationResult>();

            return !Validator.TryValidateObject(this, vc, vResults, true)
                    ? vResults.Aggregate("", (current, ve) => current + ve.ErrorMessage + Environment.NewLine)
                    : "";
        }

        protected virtual string GetValidationErrors(string columnName)
        {
            //验证上下文类实例化
            var vc = new ValidationContext(this, null, null);
            //验证请求的结果容器
            var vResults = new List<ValidationResult>();

            //检查确定指定的对象是否有效
            if (!Validator.TryValidateObject(this, vc, vResults, true))
            {
                string error = "";
                foreach (var ve in vResults)
                {
                    if (ve.MemberNames.Contains(columnName, StringComparer.CurrentCultureIgnoreCase))
                        error += ve.ErrorMessage + Environment.NewLine;
                }
                return error;
            }
            return "";
        }

        string IDataErrorInfo.Error => GetValidationErrors();

        string IDataErrorInfo.this[string columnName] => GetValidationErrors(columnName);

        /// <summary>
        /// 页面中是否所有控制数据验证正确
        /// </summary>
        public virtual bool IsValid { get; set; }
        #endregion
    }
}